

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/hello_lixi.gitee.io/img/fluid.png">
  <link rel="icon" href="/hello_lixi.gitee.io/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Mr.LI">
  <meta name="keywords" content="">
  
    <meta name="description" content="Mybatis-plus的增删改查，一对多查询">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis-plus的增删改查，一对多查询">
<meta property="og:url" content="https://xistudycode.gitee.io/hello_lixi.gitee.io/2022/12/27/Mybatis-Plus%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="Welcome to the technology blog">
<meta property="og:description" content="Mybatis-plus的增删改查，一对多查询">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/image-20221227113336543.png">
<meta property="og:image" content="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/springbootcrud%E6%95%B0%E6%8D%AE%E5%BA%93%E5%85%B3%E7%B3%BB%E5%9B%BE.png">
<meta property="og:image" content="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/springbootcrud%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84.png">
<meta property="article:published_time" content="2022-12-27T06:36:17.805Z">
<meta property="article:modified_time" content="2022-12-29T02:40:15.417Z">
<meta property="article:author" content="Mr.LI">
<meta property="article:tag" content="Mybatis-plus">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/image-20221227113336543.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>Mybatis-plus的增删改查，一对多查询 - Welcome to the technology blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/hello_lixi.gitee.io/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/hello_lixi.gitee.io/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/hello_lixi.gitee.io/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"xistudycode.gitee.io","root":"/hello_lixi.gitee.io/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/hello_lixi.gitee.io/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/hello_lixi.gitee.io/js/utils.js" ></script>
  <script  src="/hello_lixi.gitee.io/js/color-schema.js" ></script>
  

  

  

  

  

  

  

  



  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/hello_lixi.gitee.io/">
      <strong>xBlog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/hello_lixi.gitee.io/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Mybatis-plus的增删改查，一对多查询"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        Mr.LI
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-12-27 14:36" pubdate>
          2022年12月27日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          5.9k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          50 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Mybatis-plus的增删改查，一对多查询</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2022年12月29日 上午
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="实现注解方式的数据库映射和增删改查基本操作"><a href="#实现注解方式的数据库映射和增删改查基本操作" class="headerlink" title="实现注解方式的数据库映射和增删改查基本操作"></a>实现注解方式的数据库映射和增删改查基本操作</h1><p>MyBatisPlus ORM框架学习，实现注解方式的数据库映射和增删改查基本操作<br>Mybatis-plus<br>•    无侵入：只做增强不做改变，引入它不会对现有工程产生影响，如丝般顺滑<br>•    损耗小：启动即会自动注入基本 CURD，性能基本无损耗，直接面向对象操作<br>•    强大的 CRUD 操作：内置通用 Mapper、通用 Service，仅仅通过少量配置即可实现单表大部分 CRUD 操作，更有强大的条件构造器，满足各类使用需求<br>•    支持 Lambda 形式调用：通过 Lambda 表达式，方便的编写各类查询条件，无需再担心字段写错<br>•    支持主键自动生成：支持多达4种主键策略（内含分布式唯一ID生成器Sequence），可自由配置，完美解决主键问题<br>•    支持 ActiveRecord 模式：支持 ActiveRecord 形式调用，实体类只需继承 Model 类即可进行强大的 CRUD 操作<br>•    支持自定义全局通用操作：支持全局通用方法注入<br>•    内置代码生成器：采用代码或者Maven插件可快速生成Mapper、Model、Service、Controller 层代码，支持模板引擎，更有超多自定义配置等您来使用<br>•    内置分页插件：基于 MyBatis 物理分页，开发者无需关心具体操作，配置好插件之后，写分页等同于普通 List 查询<br>•    分页插件支持多种数据库：支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库<br>•    内置性能分析插件：可输出 Sql 语句以及其执行时间，建议开发测试时启用该功能，能快速揪出慢查询<br>•    内置全局拦截插件：提供全表 delete 、 update 操作智能分析阻断，也可自定义拦截规则，预防误操作<br>代码练习：springboot中集成Mybatis-plus完成员工信息的增删改查功能。<br>项目结构</p>
<p><img src="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/image-20221227113336543.png" srcset="/hello_lixi.gitee.io/img/loading.gif" lazyload alt="image-20221227113336543"></p>
<p>1.导入Mybatis-plus依赖</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java">&lt;dependency&gt;<br>    &lt;groupId&gt;com.baomidou&lt;/groupId&gt;<br>    &lt;artifactId&gt;mybatis-plus-boot-starter&lt;/artifactId&gt;<br>    &lt;version&gt;<span class="hljs-number">3.4</span><span class="hljs-number">.2</span>&lt;/version&gt;<br>&lt;/dependency&gt;<br></code></pre></td></tr></table></figure>

<p>2.创建实体 entity–staff</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@TableName(&quot;staff&quot;)</span><br><span class="hljs-meta">@Data</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Staff</span> &#123;<br><br>   <span class="hljs-meta">@TableId(value = &quot;id&quot;,type = IdType.AUTO)</span><br>   <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> id;<br><br>   <span class="hljs-meta">@TableField(&quot;name&quot;)</span><br>   <span class="hljs-keyword">private</span> String name;<br><br>   <span class="hljs-meta">@TableField(&quot;age&quot;)</span><br>   <span class="hljs-keyword">private</span> String age;<br><br>   <span class="hljs-meta">@TableField(&quot;tel&quot;)</span><br>   <span class="hljs-keyword">private</span> String tel;<br><br>   <span class="hljs-meta">@TableField(&quot;departName&quot;)</span><br>   <span class="hljs-keyword">private</span> String departName;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>3.创建mapper文件 mapper–StaffyMapper</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Repository</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">StaffMapper</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">BaseMapper</span>&lt;Staff&gt; &#123;<br><span class="hljs-comment">//继承BaseMapper,继承该接口后，无需编写 mapper.xml 文件，即可获得CRUD功能</span><br>&#125;<br></code></pre></td></tr></table></figure>



<p>4.创建service，开始使用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Resource</span><br>StaffMapper staffMapper;<br></code></pre></td></tr></table></figure>

<p>并且在启动类中扫描mapper文件<br>实体类中的@TableName用来映射数据库中的实体表，@ TableField用来映射数据库的属性。</p>
<p>Mybatis在使时的条件构造器，wrapper，可以设置查询、删除、更新的条件，<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_50975965/article/details/121384866">https://blog.csdn.net/qq_50975965/article/details/121384866</a></p>
<h1 id="实现注解方式的一对多，多对多等关联表查询"><a href="#实现注解方式的一对多，多对多等关联表查询" class="headerlink" title="实现注解方式的一对多，多对多等关联表查询"></a>实现注解方式的一对多，多对多等关联表查询</h1><p>在之前springbootcrud项目上进行修改，使用MyBatisPlus对员工进行查询，员工拥有id,name,age,tel,state属性，部门拥有id,remark,name,leader属性，一个员工属于一个部门，一个部门拥有多个员工。</p>
<img src="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/springbootcrud%E6%95%B0%E6%8D%AE%E5%BA%93%E5%85%B3%E7%B3%BB%E5%9B%BE.png" srcset="/hello_lixi.gitee.io/img/loading.gif" lazyload alt="springbootcrud数据库关系图"  />

<p>项目结构</p>
<img src="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/springbootcrud%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84.png" srcset="/hello_lixi.gitee.io/img/loading.gif" lazyload alt="springbootcrud项目结构" style="zoom:80%;" />

<p>MyBatisPlus一对多查询代码：查询部门所属的所有员工</p>
<p>1.在Depart实体类中添加stafflist属性存储查找到的员工信息</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> List&lt;Staff&gt; staffList;<br></code></pre></td></tr></table></figure>

<p>2.新建StaffMapper，用于子查询，通过员工表和关系表查找员工信息</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Mapper</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">StaffMapper</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">BaseMapper</span>&lt;Staff&gt; &#123;<br><br><br>    <span class="hljs-meta">@Select(&quot;select * from staff where staff.id = #&#123;id&#125;&quot;)</span><br>    <span class="hljs-meta">@Results(    </span><br><span class="hljs-meta">            @Result(</span><br><span class="hljs-meta">                    column = &quot;id&quot;,   </span><br><span class="hljs-meta">                    property = &quot;departList&quot;, </span><br><span class="hljs-meta">                    javaType = List.class, </span><br><span class="hljs-meta">                    many = @Many(select = &quot;com.zks.springbootcrud.mapper.DepartMapper.returnDepartment&quot;)</span><br><span class="hljs-meta"></span><br><span class="hljs-meta">            )</span><br><span class="hljs-meta">    )</span><br>    Staff_DepartVO <span class="hljs-title function_">selectStaffAndHisDepart</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;id&quot;)</span> <span class="hljs-type">int</span> id)</span>;<br>    <br>    <span class="hljs-comment">//获取返回部门所属员工信息</span><br>    <span class="hljs-meta">@Select(&quot;select staff.* from staff_depart,staff where staff_depart.depart_id = #&#123;depart_id&#125; and staff.id = staff_depart.staff_id&quot;)</span><br>    List&lt;Staff&gt; <span class="hljs-title function_">returnDepartStaffList</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;depart_id&quot;)</span> <span class="hljs-type">int</span> id)</span>;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p>3.新建DepartMapper主查询，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Mapper</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">DepartMapper</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">BaseMapper</span>&lt;Depart&gt; &#123;<br><br>    <span class="hljs-meta">@Select(&quot;select depart.* from staff_depart,depart where staff_depart.staff_id = #&#123;staff_id&#125; and depart.id = staff_depart.depart_id&quot;)</span> <span class="hljs-comment">//存疑</span><br>    List&lt;Depart&gt; <span class="hljs-title function_">returnDepartment</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;staff_id&quot;)</span> String id)</span>;<br><br><br>    <span class="hljs-comment">//查询部门所属的员工信息</span><br>    <span class="hljs-meta">@Select(&quot;select * from depart where depart.id = #&#123;id&#125;&quot;)</span><br>    <span class="hljs-meta">@Results(&#123;</span><br><span class="hljs-meta">            //将数据库表中的列和实体类中的属性对应起来，不写最后查出的结果id没有值</span><br><span class="hljs-meta">            @Result(column = &quot;id&quot;, property = &quot;id&quot;,id = true),</span><br><span class="hljs-meta">            @Result(column=&quot;id&quot;,  // 主表中的列名，这个列的值要作为查询参数传给子查询</span><br><span class="hljs-meta">                    //代表子查询的查询结果关联的实体属性,将查询到的结果存入staffList</span><br><span class="hljs-meta">                    property=&quot;staffList&quot;,  </span><br><span class="hljs-meta">                    javaType = List.class, //javaType： 子查询中的返回值类型</span><br><span class="hljs-meta">                    many = @Many(select=&quot;com.zks.springbootcrud.mapper.StaffMapper.returnDepartStaffList&quot;)</span><br><span class="hljs-meta"></span><br><span class="hljs-meta">       //@Many： 一对多、多对多使用该注解指定子查询接口方法</span><br><span class="hljs-meta">      //many = @Many(select = “com.neu.mybatisplus.dao.CarDao.returnCars”) 指定子查询接口方法</span><br><span class="hljs-meta">      //一句话版本：用column作为子查询的参数，将子查询返回值写入property</span><br><span class="hljs-meta">            )</span><br><span class="hljs-meta">    &#125;)</span><br>    Depart <span class="hljs-title function_">getDepartStaffList</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;id&quot;)</span> <span class="hljs-type">int</span> id)</span>;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>4.controller</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//获取部门所属的所有员工信息</span><br><span class="hljs-meta">@RequestMapping(&quot;/GetDepartmentStaffList/&#123;id&#125;&quot;)</span><br><span class="hljs-keyword">public</span> Depart <span class="hljs-title function_">GetDepartmentStaffList</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable(&quot;id&quot;)</span> <span class="hljs-type">int</span> id)</span>&#123;<br>    <span class="hljs-keyword">return</span> departMapper.getDepartStaffList(id);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>疑问：在进行查询的时候，查询的数据会绑定到实体类Depart中，这样就会在类中新添加新的属性stafflist，当再有新查询是还会添加新的属性（Staff类中添加额外的属性departlist），那么新查询用不到以前添加 属性时，就会赋空值，当新建StaffVO类，绑定TableName(),但是查询的结果依旧会绑定到实体类中，为什么会这样？</p>
<p><strong>解决：忘了在StaffVO类上加@Data，数据无法赋值和访问</strong></p>
<p>DepartVO</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Data</span>  <span class="hljs-comment">//要加，不然查询结果访问不到，这里可以不用使用@TableName了</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">DepartVO</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Depart</span> &#123;<br><br>    <span class="hljs-keyword">public</span> List&lt;Staff&gt; staffList;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>DepartMapper</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Mapper</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">DepartMapper</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">BaseMapper</span>&lt;Depart&gt; &#123;<br><br>    <span class="hljs-meta">@Select(&quot;select depart.* from staff_depart,depart where staff_depart.staff_id = #&#123;staff_id&#125; and depart.id = staff_depart.depart_id&quot;)</span> <span class="hljs-comment">//存疑</span><br>    List&lt;Depart&gt; <span class="hljs-title function_">returnDepartment</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;staff_id&quot;)</span> String id)</span>;<br><br><br>    <span class="hljs-comment">//查询部门所属的员工信息</span><br>    <span class="hljs-meta">@Select(&quot;select * from depart where depart.id = #&#123;id&#125;&quot;)</span><br>    <span class="hljs-meta">@Results(&#123;</span><br><span class="hljs-meta">           //将数据库表中的列和实体类中的属性对应起来，不写最后查出的结果id没有值</span><br><span class="hljs-meta">            @Result(column = &quot;id&quot;, property = &quot;id&quot;,id = true),</span><br><span class="hljs-meta">            @Result(column=&quot;id&quot;,  // 主表中的列名，这个列的值要作为查询参数传给子查询</span><br><span class="hljs-meta">                    //代表子查询的查询结果关联的实体属性,将查询到的结果存入staffList</span><br><span class="hljs-meta">                    property=&quot;staffList&quot;, </span><br><span class="hljs-meta">                    javaType = List.class, //javaType： 子查询中的返回值类型</span><br><span class="hljs-meta">                    many = @Many(select=&quot;com.zks.springbootcrud.mapper.StaffMapper.returnDepartStaffList&quot;)</span><br><span class="hljs-meta">              //@Many： 一对多、多对多使用该注解指定子查询接口方法</span><br><span class="hljs-meta">     //many = @Many(select = “com.neu.mybatisplus.dao.CarDao.returnCars”) 指定子查询接口方法</span><br><span class="hljs-meta">                    //一句话版本：用column作为子查询的参数，将子查询返回值写入property</span><br><span class="hljs-meta">            )</span><br><span class="hljs-meta">    &#125;)</span><br>    DepartVO <span class="hljs-title function_">getDepartStaffList</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;id&quot;)</span> <span class="hljs-type">int</span> id)</span>;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>StaffMapper</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Repository</span><br><span class="hljs-meta">@Mapper</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">StaffMapper</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">BaseMapper</span>&lt;Staff&gt; &#123;<br><br><br>    <span class="hljs-meta">@Select(&quot;select * from staff where staff.id = #&#123;id&#125;&quot;)</span><br>    <span class="hljs-meta">@Results(   </span><br><span class="hljs-meta">            @Result(</span><br><span class="hljs-meta">                    column = &quot;id&quot;,  </span><br><span class="hljs-meta">                    property = &quot;departList&quot;, </span><br><span class="hljs-meta">                    javaType = List.class, </span><br><span class="hljs-meta">                    many = @Many(select = &quot;com.zks.springbootcrud.mapper.DepartMapper.returnDepartment&quot;)</span><br><span class="hljs-meta"></span><br><span class="hljs-meta">            )</span><br><span class="hljs-meta">    )</span><br>    Staff_DepartVO <span class="hljs-title function_">selectStaffAndHisDepart</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;id&quot;)</span> <span class="hljs-type">int</span> id)</span>;<br><br>    <span class="hljs-comment">//获取返回部门所属员工信息</span><br>    <span class="hljs-meta">@Select(&quot;select staff.* from staff_depart,staff where staff_depart.depart_id = #&#123;depart_id&#125; and staff.id = staff_depart.staff_id&quot;)</span><br>    List&lt;Staff&gt; <span class="hljs-title function_">returnDepartStaffList</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;depart_id&quot;)</span> <span class="hljs-type">int</span> id)</span>;<br>&#125;<br></code></pre></td></tr></table></figure>


                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/hello_lixi.gitee.io/categories/java%E5%BC%80%E5%8F%91/" class="category-chain-item">java开发</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/hello_lixi.gitee.io/tags/Mybatis-plus/">#Mybatis-plus</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Mybatis-plus的增删改查，一对多查询</div>
      <div>https://xistudycode.gitee.io/hello_lixi.gitee.io/2022/12/27/Mybatis-Plus笔记/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Mr.LI</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年12月27日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/hello_lixi.gitee.io/2022/12/29/MyBatisPlu%E5%A4%9A%E6%95%B0%E6%8D%AE%E6%BA%90%E5%8A%A8%E6%80%81%E5%88%87%E6%8D%A2/" title="MyBatis-Plu多数据源动态切换">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">MyBatis-Plu多数据源动态切换</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/hello_lixi.gitee.io/2022/12/09/%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/" title="计算机基础知识">
                        <span class="hidden-mobile">计算机基础知识</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>xBolg</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>@Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/hello_lixi.gitee.io/js/events.js" ></script>
<script  src="/hello_lixi.gitee.io/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/hello_lixi.gitee.io/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/hello_lixi.gitee.io/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/hello_lixi.gitee.io/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
